package main

import (
	"flag"
	"raft-kv/logger"
	"raft-kv/raft"
	"strings"
)

type config struct {
	nodeID         string
	dir            string
	raftPeerString string
	raftPeerInfo   []raft.PeerInfo
	raftBootStrap  bool
	loggerOptions  logger.Options
	port           int //这个端口和raft的端口要有规律, 否则找不到http端口
}

func newConfig() *config {
	cfg := &config{
		nodeID:         "node0",
		dir:            "./data",
		raftPeerString: "node0=127.0.0.1:20000",
		raftPeerInfo:   []raft.PeerInfo{},
		loggerOptions:  logger.DefaultOptions(),
		port:           20001,
	}

	flag.StringVar(&cfg.nodeID, "node-id", cfg.nodeID, "raft node id, such as node0, node1 etc")
	flag.StringVar(&cfg.raftPeerString, "initial-cluster", cfg.raftPeerString, "raft cluster peers")
	flag.StringVar(&cfg.dir, "data-path", cfg.dir, "raft's log and KVDB's data path")
	flag.IntVar(&cfg.port, "http", cfg.port, "http service port")

	cfg.loggerOptions.AttachCmdFlags(flag.StringVar, flag.BoolVar)

	flag.Parse()

	cfg.raftPeerInfo = parsePeersFromFlag(cfg.raftPeerString)
	cfg.raftBootStrap = len(cfg.raftPeerInfo) > 1
	return cfg
}

func parsePeersFromFlag(val string) []raft.PeerInfo {
	peers := []raft.PeerInfo{}

	p := strings.Split(val, ",")
	for _, addr := range p {
		peer := strings.Split(addr, "=")
		if len(peer) != 2 {
			continue
		}

		peers = append(peers, raft.PeerInfo{
			ID:      strings.TrimSpace(peer[0]),
			Address: strings.TrimSpace(peer[1]),
		})
	}

	return peers
}
